from django.http import HttpResponse
from django.shortcuts import redirect
from django.utils.deprecation import MiddlewareMixin
from django.conf import settings

class AuthMiddleware(MiddlewareMixin):
    def process_request(self, request):
        # 这里用request.path_info（根据URL_WHITE_LIST）
        # 1.是否存在于白名单
        if request.path_info in settings.URL_WHITE_LIST:
            return

        # 2.是否登录（是否存在session）
        user_dict = request.session.get("user_info")
        if not user_dict:
            return redirect("login")

        # 3.给request添加session中信息
        request.user_info = user_dict

    def process_view(self, request, callback, *args, **kwargs):
        # 已路由匹配：这里才有request.resolver_match，才有resolver_match.url_name（根据URL_NAME_WHITE_LIST）
        # request
        pass


class PermissionMiddleware(MiddlewareMixin):
    def process_view(self, request, callback, *args, **kwargs):
        # 1.排除白名单
        if request.path_info in settings.URL_WHITE_LIST:
            return

        # 2.获取当前用户角色，获取其权限
        role = request.user_info["role"]
        permission_list = settings.PERMISSION_DICT[role]

        # 3.判断是否有该权限
        if not request.resolver_match.url_name in permission_list:
            # return render(request, "xxx.html")  # 也可以返回页面
            return HttpResponse("无权访问")



